import argparse
from pathlib import Path

from moviepy.editor import VideoFileClip

parser = argparse.ArgumentParser()

parser.add_argument(
    '-i',
    '--input',
    metavar='input',
    required=True,
    help='The input file path of the video'
)

parser.add_argument(
    '-s',
    '--start',
    metavar='start',
    required=True,
    help='The start time of subclip which can be expressed in like 00:05 or 01:03:05.35.'
)

parser.add_argument(
    '-e',
    '--end',
    metavar='end',
    required=False,
    help='''The end time of subclip which can be expressed in like 00:05 or 01:03:05.35.
    If end is not provided, it is assumed to be the duration of the clip (potentially infinite). 
    If end is a negative value, it is reset to clip.duration + end.
    '''
)

parser.add_argument(
    '-o',
    '--output',
    metavar='output',
    required=False,
    help='The output file path of the new clip of video'
)

args = parser.parse_args()

try:
    input_file = Path(args.input)
    if not input_file.is_absolute():
        input_file = Path.cwd() / input_file
    if input_file.exists():
        clip = VideoFileClip(args.input).subclip(args.start, args.end)  # use string, not Path
        if args.output is not None:
            output_file = Path(args.output)
            if not output_file.is_absolute():
                output_file = Path.cwd() / output_file
        else:
            output_file = input_file.parent / f'{input_file.stem}-clip{input_file.suffix}'

        clip.write_videofile(str(output_file))  # can not use Path
    else:
        print(f'No such file: {input_file}')
except Exception as e:
    print(e)

